import type { TeacherDispatchType } from '../interface'
import type { FormProps } from 'antd-mobile/es/components/form'
import type { PickerColumnItem, PickerValue } from 'antd-mobile/es/components/picker-view'
import { Button, Dialog, Empty, Form, InfiniteScroll, Input, Picker, Toast } from 'antd-mobile'
import { dispatchTeacher } from '../api'
import { SkeletonParagraphWrap } from '@/components/Common/Skeleton'
import { useFetchPageList } from '@/hooks/useFetchPageList'
import { history } from 'umi'
import { fetchDictList } from '@/api/base'
import { useLocalObservable, useObserver } from 'mobx-react'
import { getDistrict } from '@/pages/personal/api'
import { useEffect } from 'react'
import { DownOutline } from 'antd-mobile-icons'
import { rpxToPx } from '@/utils/share'
import MoreLoader from '@/components/Common/MoreLoader'
import styles from './index.module.less'
import Btn from '@/components/Global/Btn'
import NavBar from '@/components/Global/NavBar'

interface FormData {
    name?: string
    region?: string
    realname?: string
    batch?: string
}

/** 师资派遣 */
const TeacherDispatchToDo = () => {
    const queryParams = history.location.query as { id: string; code: string }

    const store = useLocalObservable(() => ({
        async fetchOptionsToStore() {
            const [divisionOptions] = await fetchDictList(['sex', 'dec_year'])
            divisionOptions
        },
    }))
    store

    const {
        dataList,
        hasMore,
        loading,
        loadMore,
        updateFilterParams,
    } = useFetchPageList<TeacherDispatchType.CanDispatchTeacher>(
        `country/group/teacher/${queryParams.id}`,
    )

    const onFinish: FormProps['onFinish'] = (formData: FormData) => {
        console.log(formData)
        updateFilterParams(formData)
    }

    const onDispatchTeacher = async (uid: number) => {
        await Dialog.confirm({
            title: '派遣确认',
            content: '是否派遣该培训师            ',
            cancelText: '取消',
            confirmText: '确认',
            onConfirm: async () => {
                const id = Number(queryParams.id)
                try {
                    await dispatchTeacher(id, uid, {
                        id,
                        uid,
                        code: queryParams.code,
                    })
                    Toast.show({ icon: 'success', content: '操作成功' })
                    history.goBack()
                } catch (error) {}
            },
        })
    }

    const PickerSex = (props: { value?: any; onChange?: (v: PickerValue) => any }) => {
        const columns = [
            [
                { label: '全部', value: '' },
                { label: '男', value: '男' },
                { label: '女', value: '女' },
            ],
        ]

        const selected = columns[0].find(item => item.value === props.value)

        return (
            <Picker
                columns={columns}
                onConfirm={([pickerValue]) => {
                    props.onChange?.(pickerValue)
                }}
            >
                {(_, actions) => (
                    <div className={styles.customSex}>
                        <Input
                            placeholder="请输入性别"
                            value={selected?.value === '' ? '' : selected?.label}
                            onClick={actions.open}
                        />
                        <DownOutline
                            fontSize={rpxToPx(28)}
                            color="#999"
                            className={styles.customSex_icon}
                        />
                    </div>
                )}
            </Picker>
        )
    }

    const PickerRegin = (props: { value?: any; onChange?: (v: PickerValue) => any }) => {
        const _store = useLocalObservable(() => ({
            columns: [] as PickerColumnItem[][],
            async fetchColumnsToStore() {
                try {
                    const { data } = await getDistrict()

                    _store.columns = [
                        [
                            { label: '全部', value: '' },
                            ...data.map(item => ({ label: item.name, value: item.code })),
                        ],
                    ]
                } catch {
                    _store.columns = []
                }
            },
        }))

        useEffect(() => {
            _store.fetchColumnsToStore()
        }, [_store])

        return useObserver(() => {
            const selected = _store.columns[0]?.find(item => item.value === props.value)
            return (
                <Picker
                    columns={_store.columns}
                    onConfirm={([pickerValue]) => {
                        props.onChange?.(pickerValue)
                    }}
                >
                    {(_, actions) => (
                        <div className={styles.customSex}>
                            <Input
                                placeholder="请输入地区"
                                value={selected?.value === '' ? '' : (selected?.label as string)}
                                onClick={actions.open}
                            />
                            <DownOutline
                                fontSize={rpxToPx(28)}
                                color="#999"
                                className={styles.customSex_icon}
                            />
                        </div>
                    )}
                </Picker>
            )
        })
    }

    return (
        <div>
            <NavBar title="派遣培训师" />

            <div className={styles.page}>
                <div className={styles.plate}>
                    <div className={styles.plate_header}>
                        培训师{queryParams.code}
                        {queryParams.code === '1' ? '（组长）' : ''}
                    </div>

                    <Form
                        layout="horizontal"
                        onFinish={onFinish}
                        footer={
                            <Button block type="submit" color="primary">
                                筛选
                            </Button>
                        }
                    >
                        <Form.Item name="name" label="姓名">
                            <Input placeholder="请输入姓名" />
                        </Form.Item>
                        <Form.Item name="sex" label="性别">
                            <PickerSex />
                        </Form.Item>
                        <Form.Item name="province_code" label="地区">
                            <PickerRegin />
                        </Form.Item>
                        <Form.Item name="batch" label="批次">
                            <Input placeholder="请输入批次" />
                        </Form.Item>
                    </Form>
                </div>

                <div className={styles.plate}>
                    <SkeletonParagraphWrap
                        animated
                        lineCount={10}
                        loading={dataList.length === 0 && loading}
                    >
                        {dataList.length > 0 && (
                            <>
                                <div>
                                    {dataList.map(item => {
                                        return (
                                            // TODO 有空封装组件
                                            <div key={item.id} className={styles.teacherCard}>
                                                <div className={styles.teacherCard_name}>
                                                    {item.realname}
                                                    {item.sex && <span>{item.sex}</span>}
                                                </div>
                                                <div className={styles.teacherCard_region}>
                                                    {item.region}
                                                </div>
                                                <div className={styles.teacherCard_idCard}>
                                                    {item.idcard}
                                                </div>

                                                <Btn
                                                    className={styles.teacherCard_operation}
                                                    size="small"
                                                    shape="rounded"
                                                    color="primary"
                                                    task={() => onDispatchTeacher(item.user_id)}
                                                >
                                                    派遣
                                                </Btn>
                                            </div>
                                        )
                                    })}
                                </div>

                                <InfiniteScroll loadMore={loadMore} hasMore={hasMore}>
                                    <MoreLoader hasMore={hasMore} />
                                </InfiniteScroll>
                            </>
                        )}

                        {dataList.length === 0 && <Empty description="暂时没有符合条件的培训师" />}
                    </SkeletonParagraphWrap>
                </div>
            </div>
        </div>
    )
}

export default TeacherDispatchToDo
